from datetime import datetime
from app import db


class Department(db.Model):
    """部门模型"""
    __tablename__ = 'department'
    
    id = db.Column(db.Integer, primary_key=True)
    parent_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=True, comment='父部门ID')
    name = db.Column(db.String(100), nullable=False, comment='部门名称')
    manager = db.Column(db.String(50), comment='负责人')
    phone = db.Column(db.String(20), comment='联系电话')
    email = db.Column(db.String(100), comment='邮箱')
    status = db.Column(db.Boolean, default=True, comment='状态(True=启用,False=禁用)')
    order_num = db.Column(db.Integer, default=0, comment='排序')
    create_time = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 自引用关系
    parent = db.relationship('Department', remote_side=[id], backref='children')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'parent_id': self.parent_id,
            'parent_name': self.parent.name if self.parent else None,
            'name': self.name,
            'manager': self.manager,
            'phone': self.phone,
            'email': self.email,
            'status': self.status,
            'order_num': self.order_num,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None
        }
    
    def to_tree_dict(self):
        """转换为树形字典"""
        return {
            'id': self.id,
            'name': self.name,
            'parent_id': self.parent_id,
            'children': [child.to_tree_dict() for child in self.children if child.status]
        } 